package com.damagez.selfrefresh.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class RefreshCacheThreadPool {
    private ExecutorService executorService;

    private static class Holder {
        private static final RefreshCacheThreadPool THREAD_POOL =
                new RefreshCacheThreadPool();
    }

    public static RefreshCacheThreadPool getInstance() {
        return Holder.THREAD_POOL;
    }

    public RefreshCacheThreadPool() {
        executorService = Executors.newFixedThreadPool(getSuitableThreadCount(), new ThreadFactory() {
            AtomicInteger count = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setDaemon(true);
                t.setName("com.damage.cache.refresh-" + count.getAndIncrement());
                return t;
            }
        });
    }

    public void execute(Runnable runnable) {
        executorService.execute(runnable);
    }

    private final static int THREAD_MULTIPLIER = 2;

    /**
     * 通过内核数，算出合适的线程数；1.5-2倍cpu内核数
     *
     * @return thread count
     */
    public static int getSuitableThreadCount() {
        final int coreCount = Runtime.getRuntime().availableProcessors();
        int workerCount = 1;
        while (workerCount < coreCount * THREAD_MULTIPLIER) {
            workerCount <<= 1;
        }
        return workerCount;
    }
}
